package com.doyutu.seed.controller;

import com.doyutu.seed.entity.result.Result;
import com.doyutu.seed.entity.vo.User;
import javax.validation.Valid;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author DoyuTu
 * @version 0.0.1
 * spring-boot-project-seed
 */
@RestController
public class LoginController {

    @RequestMapping("login")
    public Object login(@Valid User user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        //记住密码
        token.setRememberMe(user.isRememberMe());
        try {
            subject.login(token);
        } catch (Exception e) {
            return Result.fail("登录失败，用户名或密码错误");
        }
        return user.toString();
    }

    @RequestMapping("logout")
    public Object logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject == null) {
            return Result.fail();
        }
        subject.logout();
        return Result.ok();
    }

}
